package com.echat.serviceapigateway.security.model.authentication;

import com.echat.commonlib.constant.ErrorCode;
import com.echat.commonlib.exception.exc.ValidateFailedException;
import com.echat.serviceapigateway.security.model.BaseModel;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.NameStyle;
import tk.mybatis.mapper.code.Style;

import javax.persistence.Column;
import javax.persistence.Id;
import java.time.LocalDateTime;

/**
 * Created by chenmohan on 2018/08/30
 *
 * @description
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@NameStyle(Style.camelhumpAndLowercase)
@JsonIgnoreProperties(value = {"id", "userId", "getTimes", "createTime", "modifyTime", "refreshToken", "refreshTokenExpire"})
public class Token extends BaseModel {

    @Id
    private Long id;

    private Long userId;

    private String accessToken;

    private String refreshToken;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm")
    private LocalDateTime accessTokenExpire;

    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm")
    private LocalDateTime refreshTokenExpire;

    private int getTimes;

    @Column(name = "create_datetime")
    @JsonIgnore
    protected LocalDateTime createTime;

    @Column(name = "modify_datetime")
    @JsonIgnore
    protected LocalDateTime modifyTime;

    public void checkUserIdNotNull() {
        if (this.id == null) {
            throw new ValidateFailedException(ErrorCode.User.USERNAME_NOT_NULL, "field[userId] must not be null");
        }
    }
}
